<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 专业文章生成器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563EB',
                        secondary: '#1E40AF',
                        accent: '#3B82F6',
                        success: '#059669',
                        warning: '#D97706',
                        error: '#DC2626'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 h-screen overflow-hidden" x-data="articleGenerator()">
    <!-- 顶部导航栏 -->
    <nav class="bg-white border-b border-gray-200 h-16 flex items-center px-6">
        <div class="flex items-center space-x-3">
            <div class="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
                <i class="fas fa-feather-alt text-white text-sm"></i>
            </div>
            <h1 class="text-xl font-semibold text-gray-900">AI 专业文章生成器</h1>
        </div>
        <div class="ml-auto flex items-center space-x-4">
            <div class="flex items-center space-x-2 text-sm text-gray-600">
                <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                <span>AI 服务在线</span>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="flex h-[calc(100vh-4rem)]">
        
        <!-- 左侧AI对话面板 -->
        <div class="w-80 bg-white border-r border-gray-200 flex flex-col">
            <!-- 需求输入区域组件 -->
            <div id="requirement-input-component" class="flex-1 flex flex-col"></div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="flex-1 bg-white flex">
            
            <!-- 文章大纲 -->
            <div class="w-80 border-r border-gray-200 flex flex-col">
                <div class="p-6 border-b border-gray-100">
                    <h3 class="text-lg font-medium text-gray-900">文章大纲</h3>
                </div>

                <div class="flex-1 overflow-y-auto">
                    <div x-show="!outline.length && !isGenerating" class="p-6 text-center text-gray-400">
                        <i class="fas fa-sitemap text-2xl mb-3"></i>
                        <p class="text-sm">描述需求后开始生成大纲</p>
                    </div>

                    <div x-show="isGenerating && !outline.length" class="p-6 text-center">
                        <div class="animate-spin w-6 h-6 border-2 border-primary border-t-transparent rounded-full mx-auto mb-3"></div>
                        <p class="text-sm text-gray-500">正在分析需求并生成大纲...</p>
                    </div>

                    <div x-show="outline.length" class="p-4 space-y-2">
                        <template x-for="(section, index) in outline" :key="index">
                            <div 
                                class="p-3 rounded-md border cursor-pointer transition-all"
                                :class="selectedSection === index ? 'bg-blue-50 border-primary' : 'border-gray-200 hover:border-gray-300'"
                                @click="selectedSection = index"
                            >
                                <div class="flex items-center space-x-2">
                                    <span class="w-5 h-5 bg-primary text-white rounded-full flex items-center justify-center text-xs font-medium" x-text="index + 1"></span>
                                    <h4 class="font-medium text-gray-900 flex-1 text-sm" x-text="section.title"></h4>
                                    <i x-show="section.completed" class="fas fa-check text-success text-xs"></i>
                                </div>
                                <div x-show="section.keyPoints && section.keyPoints.length" class="mt-2 ml-7">
                                    <template x-for="point in section.keyPoints" :key="point">
                                        <p class="text-xs text-gray-600 mb-1" x-text="'• ' + point"></p>
                                    </template>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>

            <!-- 文章正文 -->
            <div class="flex-1 flex flex-col">
                <div class="p-6 border-b border-gray-100 flex items-center justify-between">
                    <h3 class="text-lg font-medium text-gray-900">文章正文</h3>
                    <div x-show="article" class="flex space-x-2">
                        <button @click="copyArticle()" class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-md text-sm transition-colors">
                            <i class="fas fa-copy mr-1"></i>复制
                        </button>
                        <button @click="downloadArticle()" class="px-3 py-1.5 bg-primary hover:bg-secondary text-white rounded-md text-sm transition-colors">
                            <i class="fas fa-download mr-1"></i>下载
                        </button>
                    </div>
                </div>

                <div class="flex-1 overflow-y-auto p-6">
                    <div x-show="!article && !isGenerating" class="text-center py-20 text-gray-400">
                        <i class="fas fa-file-alt text-3xl mb-4"></i>
                        <p class="text-lg font-medium mb-2">专业文章即将呈现</p>
                        <p class="text-sm">详细描述您的需求，让AI为您创作高质量内容</p>
                    </div>

                    <div x-show="isGenerating && !article" class="text-center py-20">
                        <div class="animate-spin w-12 h-12 border-3 border-primary border-t-transparent rounded-full mx-auto mb-4"></div>
                        <p class="text-lg font-medium text-gray-600 mb-2">AI 正在精心创作</p>
                        <p class="text-sm text-gray-500">请稍候，好文章值得等待...</p>
                    </div>

                    <div x-show="article" class="prose prose-lg max-w-none">
                        <div x-html="article" class="article-content"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .article-content {
            line-height: 1.7;
        }
        .article-content h1 {
            @apply text-2xl font-bold text-gray-900 mb-4 pb-2 border-b border-gray-200;
        }
        .article-content h2 {
            @apply text-xl font-semibold text-gray-800 mt-6 mb-3;
        }
        .article-content h3 {
            @apply text-lg font-medium text-gray-700 mt-4 mb-2;
        }
        .article-content p {
            @apply text-gray-600 mb-3 leading-relaxed;
        }
        .article-content ul, .article-content ol {
            @apply mb-3 pl-5;
        }
        .article-content li {
            @apply mb-1 text-gray-600;
        }
        .article-content code {
            @apply bg-gray-100 px-1.5 py-0.5 rounded text-sm font-mono;
        }
        .article-content pre {
            @apply bg-gray-900 text-gray-100 p-4 rounded-md overflow-x-auto mb-4;
        }
        .article-content blockquote {
            @apply border-l-4 border-primary pl-4 italic text-gray-600 mb-4;
        }
    </style>

    <script>
        // 动态加载组件
        async function loadComponent(elementId, componentPath) {
            try {
                const response = await fetch(componentPath);
                const html = await response.text();
                document.getElementById(elementId).innerHTML = html;
            } catch (error) {
                console.error(`加载组件失败: ${componentPath}`, error);
            }
        }

        // 页面加载完成后加载组件
        document.addEventListener('DOMContentLoaded', async function() {
            await loadComponent('requirement-input-component', '/static/components/requirement-input.html');
        });

        function articleGenerator() {
            return {
                // 输入数据
                userRequirement: '',
                currentMessage: '',
                
                // 对话数据
                conversation: [],
                
                // 状态管理
                isGenerating: false,
                progress: 0,
                currentStep: '',
                selectedSection: 0,
                taskId: null,
                
                // 内容数据
                outline: [],
                article: '',
                logs: [],
                
                // 更新标记
                lastShownPrompt: null,
                outlineUpdated: false,
                contentUpdated: false,
                qualityUpdated: false,
                
                // 发送消息
                async sendMessage() {
                    const message = this.currentMessage.trim();
                    if (!message || this.isGenerating) return;
                    
                    // 添加用户消息到对话
                    this.addToConversation('user', message);
                    
                    // 清空输入框
                    this.currentMessage = '';
                    
                    // 设置需求并开始生成
                    this.userRequirement = message;
                    await this.generateArticle();
                },
                
                // 设置快捷提示
                setQuickPrompt(prompt) {
                    this.currentMessage = prompt;
                },
                
                // 添加消息到对话
                addToConversation(type, content, subType = null, progress = 0) {
                    this.conversation.push({
                        id: Date.now() + Math.random(),
                        type: type,
                        subType: subType,
                        content: content,
                        progress: progress,
                        timestamp: new Date().toLocaleTimeString()
                    });
                    
                    // 滚动到底部
                    this.$nextTick(() => {
                        const conversationArea = document.getElementById('conversation-area');
                        if (conversationArea) {
                            conversationArea.scrollTop = conversationArea.scrollHeight;
                        }
                    });
                },
                
                // 系统消息样式
                getSystemMessageStyle(subType) {
                    const styles = {
                        'info': 'bg-blue-50 text-blue-800 border-blue-300',
                        'success': 'bg-green-50 text-green-800 border-green-300',
                        'warning': 'bg-yellow-50 text-yellow-800 border-yellow-300',
                        'error': 'bg-red-50 text-red-800 border-red-300'
                    };
                    return styles[subType] || styles.info;
                },
                
                // 系统消息图标
                getSystemMessageIcon(subType) {
                    const icons = {
                        'info': 'fas fa-info-circle text-blue-500',
                        'success': 'fas fa-check-circle text-green-500',
                        'warning': 'fas fa-exclamation-triangle text-yellow-500',
                        'error': 'fas fa-times-circle text-red-500'
                    };
                    return icons[subType] || icons.info;
                },
                
                // 添加系统消息
                addSystemMessage(type, message, subType = 'info') {
                    this.addToConversation('system', message, subType);
                },
                
                // 添加进度消息
                addProgressMessage(message, progress) {
                    // 更新或添加进度消息
                    const existingProgressIndex = this.conversation.findIndex(msg => msg.type === 'progress');
                    if (existingProgressIndex >= 0) {
                        this.conversation[existingProgressIndex].content = message;
                        this.conversation[existingProgressIndex].progress = progress;
                        this.conversation[existingProgressIndex].timestamp = new Date().toLocaleTimeString();
                    } else {
                        this.addToConversation('progress', message, null, progress);
                    }
                },
                
                // 添加状态消息
                addStatusMessage(message) {
                    this.addToConversation('status', message);
                },
                
                // 清除对话历史
                clearConversation() {
                    this.conversation = [];
                    this.userRequirement = '';
                    this.currentMessage = '';
                    this.outline = [];
                    this.article = '';
                    this.logs = [];
                    this.isGenerating = false;
                    this.progress = 0;
                },
                
                // 生成文章
                async generateArticle() {
                    const requirement = this.userRequirement.trim();
                    
                    if (!requirement) {
                        this.addToConversation('ai', '请告诉我您想要创作什么样的文章 🤔');
                        return;
                    }
                    
                    try {
                        // 重置状态
                        this.isGenerating = true;
                        this.progress = 0;
                        this.outline = [];
                        this.article = '';
                        this.logs = [];
                        
                        // 重置更新标记
                        this.lastShownPrompt = null;
                        this.outlineUpdated = false;
                        this.contentUpdated = false;
                        this.qualityUpdated = false;
                        
                        // AI回复确认消息
                        this.addToConversation('ai', '收到您的需求！让我来为您创作一篇专业文章 ✨<br><br>我会依次完成以下步骤：<br>📋 分析需求<br>🎯 制定大纲<br>✍️ 撰写内容<br>🔍 质量检查');
                        
                        // 添加系统消息
                        this.addSystemMessage('info', '正在初始化任务创建流程...');
                        
                        // 创建任务
                        const createResponse = await fetch('/api/createtask', {
                            method: 'POST',
                            headers: { 
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({
                                requirement: requirement,
                                task_type: 'report_generation',
                                priority: 'normal'
                            })
                        });

                        const createResult = await createResponse.json();
                        console.log('API 返回结果:', createResult);
                        
                        if (!createResult.success) {
                            throw new Error(createResult.error || '任务创建失败');
                        }
                        
                        if (!createResult.data || !createResult.data.id) {
                            console.error('API 返回数据结构:', createResult);
                            throw new Error('API 返回的数据格式不正确');
                        }
                        
                        this.taskId = createResult.data.id;
                        this.addSystemMessage('success', `任务创建成功，任务ID: ${this.taskId}`, 'success');
                        this.addStatusMessage('开始执行文章生成任务...');
                        
                        // 开始轮询任务状态
                        await this.pollTaskStatus();
                        
                    } catch (error) {
                        console.error('生成报告时发生错误:', error);
                        this.addSystemMessage('error', `错误: ${error.message}`, 'error');
                        this.addToConversation('ai', `抱歉，生成过程中遇到了问题：${error.message} 😔<br><br>请稍后重试或重新描述您的需求。`);
                        this.progress = 0;
                    } finally {
                        this.isGenerating = false;
                    }
                },
                
                // 轮询任务状态
                async pollTaskStatus() {
                    if (!this.taskId) {
                        throw new Error('没有有效的任务ID');
                    }
                    
                    let lastProgress = 0;
                    
                    while (true) {
                        try {
                            const statusResponse = await fetch(`/api/tasks/${this.taskId}/status`, {
                                headers: {
                                    'Accept': 'application/json'
                                }
                            });
                            
                            if (!statusResponse.ok) {
                                const errorText = await statusResponse.text();
                                console.error('状态查询错误响应:', errorText);
                                throw new Error('查询任务状态失败');
                            }
                            
                            const statusResult = await statusResponse.json();
                            
                            if (!statusResult.success) {
                                throw new Error(statusResult.error || '获取状态失败');
                            }
                            
                            const taskData = statusResult;
                            
                            // 更新界面状态
                            this.updateTaskProgress(taskData);
                            
                            // 检查进度变化，发送AI消息
                            if (this.progress > lastProgress) {
                                let progressMessage = '';
                                if (this.progress >= 25 && lastProgress < 25) {
                                    progressMessage = '📋 需求分析完成，正在制定文章大纲...';
                                    this.addToConversation('ai', progressMessage);
                                } else if (this.progress >= 50 && lastProgress < 50) {
                                    progressMessage = '🎯 大纲制定完成，开始撰写文章内容...';
                                    this.addToConversation('ai', progressMessage);
                                } else if (this.progress >= 75 && lastProgress < 75) {
                                    progressMessage = '✍️ 内容撰写完成，正在进行质量检查...';
                                    this.addToConversation('ai', progressMessage);
                                }
                                
                                // 更新进度消息
                                this.addProgressMessage(`正在执行第${Math.ceil(this.progress/25)}个步骤...`, this.progress);
                                lastProgress = this.progress;
                            }
                            
                            // 检查是否完成
                            if (taskData.status === 'completed') {
                                this.addSystemMessage('success', '文章生成任务完成！', 'success');
                                this.addToConversation('ai', '🎉 文章创作完成！<br><br>我已经为您生成了一篇高质量的专业文章。您可以在右侧查看完整内容，也可以继续与我对话来调整和完善。');
                                break;
                            } else if (taskData.status === 'failed') {
                                throw new Error(taskData.error || '任务执行失败');
                            }
                            
                            // 等待后继续轮询
                            await new Promise(resolve => setTimeout(resolve, 2000));
                            
                        } catch (error) {
                            this.addSystemMessage('error', `状态查询错误: ${error.message}`, 'error');
                            break;
                        }
                    }
                },
                
                // 更新进度的方法
                updateTaskProgress(taskData) {
                    console.log('收到任务数据:', taskData);
                    
                    // 更新代理状态 - 完全基于API返回的数据
                    if (taskData.agent_status) {
                        let completedAgents = 0;
                        const totalAgents = 4;
                        const agentNames = {
                            'planner': '需求分析代理',
                            'structure': '结构代理', 
                            'writer': '写作代理',
                            'quality': '质量检查代理'
                        };
                        
                        // 遍历所有代理状态
                        for (const [agent, status] of Object.entries(taskData.agent_status)) {
                            if (status === 'completed') {
                                completedAgents++;
                                
                                // 根据不同代理发送不同的状态消息
                                if (agent === 'planner') {
                                    this.addStatusMessage(`✅ 需求分析完成 - 已优化您的需求为专业prompt`);
                                    
                                    // 显示优化后的prompt（来自API）
                                    if (taskData.optimized_prompt && taskData.optimized_prompt !== this.lastShownPrompt) {
                                        this.lastShownPrompt = taskData.optimized_prompt;
                                        this.addToConversation('ai', `📋 需求分析完成！我已经将您的需求优化为更专业的描述：<br><br><div class="bg-gray-50 p-3 rounded-md text-sm mt-2 border-l-4 border-blue-500"><strong>优化后的需求：</strong><br>${taskData.optimized_prompt}</div><br>现在我将基于这个优化后的需求为您创作文章。`);
                                    }
                                } else if (agent === 'structure') {
                                    this.addStatusMessage(`✅ 文章结构规划完成`);
                                } else if (agent === 'writer') {
                                    this.addStatusMessage(`✅ 文章内容撰写完成`);
                                } else if (agent === 'quality') {
                                    this.addStatusMessage(`✅ 质量检查完成`);
                                }
                            } else if (status === 'failed') {
                                this.addSystemMessage('error', `❌ ${agentNames[agent] || agent}执行失败`, 'error');
                            } else if (status === 'processing') {
                                if (agent === 'planner') {
                                    this.addStatusMessage(`🔍 正在分析您的需求并优化prompt...`);
                                } else if (agent === 'structure') {
                                    this.addStatusMessage(`📋 正在规划文章结构...`);
                                } else if (agent === 'writer') {
                                    this.addStatusMessage(`✍️ 正在撰写文章内容...`);
                                } else if (agent === 'quality') {
                                    this.addStatusMessage(`🔍 正在进行质量检查...`);
                                }
                            }
                        }
                        
                        // 计算进度（基于完成的代理数量）
                        this.progress = (completedAgents / totalAgents) * 100;
                        
                        // 更新进度消息
                        if (this.progress > 0 && this.progress < 100) {
                            this.addProgressMessage(`正在执行第${completedAgents + 1}个步骤...`, this.progress);
                        }
                    }
                    
                    // 更新大纲（来自API）
                    if (taskData.plan && !this.outlineUpdated) {
                        try {
                            const planData = typeof taskData.plan === 'string' ? JSON.parse(taskData.plan) : taskData.plan;
                            if (planData.sections) {
                                this.outline = planData.sections.map((section, index) => ({
                                    title: section.title,
                                    keyPoints: section.key_points || [],
                                    completed: false
                                }));
                                this.outlineUpdated = true;
                                this.addStatusMessage('📋 文章大纲已生成');
                            }
                        } catch (e) {
                            console.error('解析大纲失败:', e);
                        }
                    }
                    
                    // 更新文章内容（来自API）
                    if (taskData.content && !this.contentUpdated) {
                        this.article = taskData.content;
                        this.outline = this.outline.map(section => ({...section, completed: true}));
                        this.contentUpdated = true;
                        this.addStatusMessage('📝 文章内容已生成');
                    }
                    
                    // 更新质量评分（来自API）
                    if (taskData.quality_score !== undefined && !this.qualityUpdated) {
                        const score = Number(taskData.quality_score).toFixed(1);
                        this.addStatusMessage(`🎯 质量评分: ${score}/10`);
                        this.qualityUpdated = true;
                    }
                },
                
                // 从需求中提取关键词
                extractKeywordFromRequirement() {
                    const requirement = this.userRequirement.toLowerCase();
                    if (requirement.includes('人工智能') || requirement.includes('ai') || requirement.includes('机器学习')) {
                        return '人工智能';
                    } else if (requirement.includes('区块链') || requirement.includes('blockchain')) {
                        return '区块链';
                    } else {
                        const words = this.userRequirement.split(/[，。、\s]+/);
                        return words.find(word => word.length > 1) || '技术';
                    }
                },
                
                // 复制文章
                copyArticle() {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = this.article;
                    const text = tempDiv.textContent || tempDiv.innerText || '';
                    
                    navigator.clipboard.writeText(text).then(() => {
                        this.addSystemMessage('success', '📋 文章内容已复制到剪贴板', 'success');
                    }).catch(() => {
                        this.addSystemMessage('error', '❌ 复制失败，请手动选择复制', 'error');
                    });
                },
                
                // 下载文章
                downloadArticle() {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = this.article;
                    const text = tempDiv.textContent || tempDiv.innerText || '';
                    
                    const keyword = this.extractKeywordFromRequirement();
                    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${keyword}_专业文章.txt`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    this.addSystemMessage('success', '💾 文章已下载到本地', 'success');
                }
            }
        }
    </script>
</body>
</html> 